import {
	useRequest
} from "./request.js";

import {
	useUserStore
} from "../stores/useUserStore.js";

export const useUserApis = () => {
	const userStore = useUserStore();
	const request = useRequest();

	const config = {
		header: {
			authorization: userStore.token
		}
	}

	function list() {
		return request.get("/api/users", config);
	}

	// 登陆
	async function login({
		mobile,
		password
	}) {
		const {
			token,
			user
		} = await request.post("/api/auth/login", {
			mobile,
			password
		});

		// 保存token和user
		userStore.setToken(token);
		userStore.setUser(user);

		return user;
	}

	// 修改密码
	function changePassword({
		oldPassword,
		newPassword
	}) {
		const id = userStore.id;
		return request.pathch(`/api/users/${id}/password`, {
			data: {
				oldPassword,
				newPassword
			},
			...config
		})
	}

	/**
	 * 管理员添加用户
	 * 默认密码为123456
	 */
	function register({
		name,
		mobile,
	}) {
		const password = "123456";
		return request.post("/api/users", {
			name,
			mobile,
			password
		}, config);
	}

	// 管理员重置密码为123456
	function resetPassword(userId) {
		return request.put(`/api/users/${userId}`, {
			data: {
				password: "123456",
			},
			...config
		});
	}
	// 禁用、启用用户
	function updateStatus({
		userId,
		isDisable
	}) {
		return request.pathch(`/api/users/${userId}/status`, {
			data: {
				isDisable
			},
			...config
		});
	}
	// 删除用户
	function deleteUser(userId) {
		return request.delete(`/api/users/${userId}`, config);
	}


	return {
		list,
		login,
		register,
		changePassword,
		resetPassword,
		updateStatus,
		delete: deleteUser,
	}
}